import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as _ from "lodash";
import { List } from "immutable";
import ProductGrid from "components/productGrid";
import ProductInfo from "../models/ProductInfo";
import Button from 'react-bootstrap/es/Button';
import FormControl from 'react-bootstrap/es/FormControl';
import FormGroup from 'react-bootstrap/es/FormGroup';
import ControlLabel from "react-bootstrap/es/ControlLabel";
import InputGroup from "react-bootstrap/es/InputGroup";
import Form from "react-bootstrap/es/Form";
import Row from "react-bootstrap/es/Row";
import Col from "react-bootstrap/es/Col";
import Checkbox from "react-bootstrap/es/Checkbox";
var styles = require('./sale-add.less');


class App extends React.PureComponent<any, any> {
  constructor(props, context) {
    super(props, context);

    this.state = {
      products: List<ProductInfo>(_.map(Array(6), () => new ProductInfo())),
      amtCount: 0,
      totalCount: 0,
      discountRate: 100,
      discountAmt: 0,
      otherFee: 0,
      faReceAmt: 0
    }
  }

  static childContextTypes = {
    addOneAfter: React.PropTypes.func,
    deleteOne: React.PropTypes.func,
    editProduct: React.PropTypes.func,
  }

  getChildContext() {
    return {
      addOneAfter: (index: number) => {
        const products = this.state.products;
        this.setState({ products: products.insert(index + 1, new ProductInfo()) })
      },
      deleteOne: (index: number) => {
        const products = this.state.products;
        this.setState({ products: products.delete(index) });
      },
      editProduct: (productInfo: ProductInfo, propName: string, propValue: any) => {
        const products = this.state.products;
        const index = products.findIndex(product => product.id == productInfo.id);

        const temp = {};
        let newAmtCount = 0;
        let newTotalCount = 0;
        temp[propName] = propValue;
        if (propName == "eachSaleAmt") {
          const eachSaleAmt = propValue;
          temp['productPrice'] = eachSaleAmt / productInfo.product_count;
        }

        const newProducts = products.update(index, () => _.assign(new ProductInfo(), productInfo, temp));

        newProducts.forEach((product: ProductInfo) => {
          newTotalCount += product.product_count;
          newAmtCount += product.eachSaleAmt;
        })

        const newDiscountAmt = (newAmtCount * this.state.discountRate) / 100;
        this.setState({
          products: newProducts,
          amtCount: newAmtCount,
          totalCount: newTotalCount,
          discountAmt: newDiscountAmt,
          faReceAmt: this.state.otherFee + newDiscountAmt
        });
      }
    }
  }

  render() {
    const products = this.state.products;
    return (
      <div className="main">
        <div className="actionArea mb10 wf98" style={{ zIndex: 9999, top: "-10px", padding: "10px 0px", position: "fixed" }}>
          <div style={{ display: "inline-block" }} className="fl topButtonBg">
            <Button bsStyle="primary" bsSize="small" className="fl mr5">选择商品</Button>
            <Button id="importProduct" bsSize="small" className="withIcon fl">
              <span className="icon importIcon"></span>
              <span>导入</span>
            </Button>
          </div>
          <div className="fr topButtonBg">
            <a className="button fr processing loadsave hidden" >正在保存...</a>
            <Button bsStyle="primary" bsSize="small" className=" blueButton fr savebtn">保存并新增(F9)</Button>
            <Button bsSize="small" className="fr mr5 savebtn">保存(Ctrl+S)</Button>
            <Button bsSize="small" className="fr mr5">历史单据</Button>
          </div>
        </div>
        <div className="whiteBox receipts">
          <Row className="header" style={{ paddingTop: "10px", paddingBottom: "20px" }}>
            <Col md={4}>
              <Form componentClass="div" inline>
                <FormGroup bsSize="small" className="mr10">
                  <span className="mr5 font12">出库仓库</span>
                  <FormControl bsSize="small" componentClass="select" style={{ width: '110px' }} placeholder="请选择仓库">
                    <option value="select">默认仓库</option>
                    <option value="other">...</option>
                  </FormControl>
                </FormGroup>
                <FormGroup bsSize="small">
                  <span className="mr5 font12">客户</span>
                  <FormControl type="text" style={{ width: '140px' }} />
                </FormGroup>
              </Form>
            </Col>
            <Col md={4} className="title">
              <span>商品销售单</span>
            </Col>
            <Col md={4} className="textRight">
              <span className="mr5">单据编号:</span>
              <input className="codeEdit enterindex" name="txbBusiNo" id="txbBusiNo" type="text" defaultValue="XSD20170823000" maxLength={30} />
              <input type="hidden" id="billNoSettingId" value="3DFC6183-4A5F-4D40-B60C-ABA4C1C69EB3" />
            </Col>
          </Row>

          <Row style={{ paddingTop: "12px", paddingBottom: "12px" }}>
            <Col md={6}>
              <Form componentClass="div" inline>
                <FormGroup bsSize="small" className="mr10">
                  <span className="mr5 font12">销售类型</span>
                  <FormControl bsSize="small" componentClass="select" style={{ width: '110px' }} placeholder="请选择销售类型">
                    <option value="select">零售</option>
                    <option value="other">批发</option>
                  </FormControl>
                </FormGroup>
                <Checkbox inline className="btn btn-default" style={{ padding: '4px 30px' }}>保存后打印</Checkbox>
                <Checkbox inline className="btn btn-default" style={{ padding: '4px 30px' }}>送货</Checkbox>
              </Form>
            </Col>
            <Col md={6} className="textRight">
              <Form componentClass="div" inline>
                <FormGroup bsSize="small" className="mr10">
                  <span className="mr5 font12">经手人</span>
                  <FormControl bsSize="small" componentClass="select">
                    <option value="select">员工：管理员</option>
                  </FormControl>
                </FormGroup>
                <FormGroup bsSize="small" className="mr10">
                  <span className="mr5 font12">业务日期</span>
                  <FormControl bsSize="small">
                  </FormControl>
                </FormGroup>
              </Form>
            </Col>
          </Row>
          <ProductGrid products={products} ></ProductGrid>
        </div >
      </div >
    );
  }
}


$(function () {
  ReactDOM.render(
    <App></App>
    , document.getElementById('content')
  );
})



  // var ItemView = Backbone.View.extend({
  //   tagName: "tr",
  //   template: $('#product_template').html(),
  //   initialize: function () {
  //     this.model.bind('destroy', this.remove, this);
  //     this.model.bind('change', this.render, this);
  //     this.model.bind("focus", this.focus, this);
  //   },
  //   events: {
  //     "mouseover": "onMouseover",
  //     "mouseout": "onMouseout",
  //     "click .plusLite": "addRow",
  //     "click .delLite": "deleteRow",
  //     //"change input[name = 'showProductName']" : "changeProductName",
  //     "change input[name = 'showProductCode']": "changeProductCode",
  //     "change input[name = 'SalePrice']": "changeSalePrice",
  //     "change input[name = 'SaleCount']": "changeSaleCount",
  //     "change input[name = 'UnitName']": "changeUnitName",
  //     "change input[name = 'EachSaleAmt']": "changeEachSaleAmt",
  //     "change input[name = 'EachSaleRemark']": "changeEachSaleRemark",
  //     "click .choseGoods": "selectProduct"
  //   },
  //   onMouseover: function () {
  //     this.$('.choseGoods').show();
  //   },

  //   onMouseout: function () {
  //     this.$('.choseGoods').hide();
  //   },
  //   addRow: function () {
  //     productView.addOneAfter(this.model.get("index"));
  //   },

  //   deleteRow: function () {
  //     if (products.length > 1) {
  //       this.model.destroy();
  //     }
  //   },
  //   changeProductName: function (event) {
  //     var val = this.$("input[name = 'showProductName']").val();
  //     this.model.set("productName", val);
  //   },
  //   changeProductCode: function (event) {
  //     var val = this.$("input[name = 'showProductCode']").val();
  //     this.model.set("productCode", val);
  //   },

  //   changeSalePrice: function (event) {
  //     var val = this.$("input[name = 'SalePrice']").val();
  //     this.model.set("productPrice", val);
  //     calSaleAmt(this.model);
  //   },
  //   changeSaleCount: function (event) {
  //     var val = this.$("input[name = 'SaleCount']").val();
  //     this.model.set("productCount", val);
  //     calSaleAmt(this.model);
  //   },
  //   changeUnitName: function (event) {
  //     var val = this.$("input[name = 'UnitName']").val();
  //     this.model.set("unit", val);
  //   },
  //   changeEachSaleAmt: function (event) {
  //     var val = this.$("input[name = 'EachSaleAmt']").val();
  //     this.model.set("eachSaleAmt", val);
  //     calSalePrice(this.model);
  //   },
  //   changeEachSaleRemark: function (event) {
  //     var val = this.$("input[name = 'EachSaleRemark']").val();
  //     this.model.set("eachSaleRemark", val);
  //   },

  //   //选择商品
  //   selectProduct: function () {
  //     SelectProductByBusi(this.model.get("index"), "Sale");
  //   },
  //   focus: function (selector) {
  //     $(this.el).find(selector).focus();
  //   },
  //   //智能提示
  //   autoComplete: function (obj) {
  //     var view = this;
  //     var index = obj.get("index");
  //     var productheader = { mnCode: "助记符", productName: "商品名称", productForm: "规格", productStock: "库存" };
  //     $(this.el).find("input:text[name='showProductName']").each(function () {
  //       $(this).autoComplete({
  //         header: productheader,
  //         url: "/ProductInfo/getProduct",
  //         width: 400,
  //         selected: function (o) {
  //           var jsonn = [];
  //           o["productCount"] = 1;
  //           jsonn.push(o);
  //           SelectProductOK(jsonn, index);

  //           //如果最后一行，则新增一行
  //           if (index == products.length) {
  //             view.addRow();
  //           }
  //           //设置下一行焦点
  //           productView.setFocus(index + 1, "input[name='showProductName']");
  //         }
  //       });
  //     });
  //   },
  //   render: function () {
  //     var template = _.template(this.template, this.model.toJSON());
  //     $(this.el).html(template);
  //     this.autoComplete(this.model);
  //     $(this.el).addClass("productItem");
  //     if (this.model.get("readonly")) {
  //       $(this.el).find("input:text[autoComplete='off']").css({ "border": "#000000 0px solid" });
  //       $(this.el).find('input[name="showProductCode"]').attr("readonly", "readonly");
  //       $(this.el).find('input[name="showProductCode"]').attr("unselectable", "on");
  //     }
  //     return this;
  //   }
  // });

//   var ProductView = Backbone.View.extend({
//     amtCount: 0,
//     totalCount: 0,
//     otherFee: 0,
//     faReceAmt: 0,
//     el: $('body'),
//     initialize: function () {
//       for (var i = 0; i < 6; i++) {
//         products.add(new Product());
//       }

//       var copySaleId = this.$("#CopySaleId").val();
//       if (copySaleId != 0) {
//         this.copyFromSale(copySaleId);
//       }
//       this.render();
//     },
//     events: {
//       "change  #OtherFee": "calDiscountAmt",
//       "change  #SaleAmt": "calDiscountAmt",
//       "click .SaveDataToList": "SaveDataToList",
//       "click .SaveData": "SaveData",
//     },
//     render: function () {
//       this.$("#tabProducts .productItem").remove();
//       for (var i = 0; i < products.length; i++) {
//         var product = products.at(i);
//         this.addOne(product);
//       }
//     },

//     //添加一个任务到页面id为todo-list的div/ul中
//     addOne: function (product) {
//       var view = new ItemView({ model: product });
//       this.$("#tabProducts #total").before(view.render().el);
//     },
//     clearOne: function (product) {
//       product.destroy();
//     },
//     addOneAfter: function (index) {
//       var product = new Product();
//       products.add(product, { at: index });
//       this.render();
//     },

//     clearAll: function () {
//       products.each(this.clearOne);
//     },

//     allAll: function () {
//       products.each(this.addOne);
//     },

//     selectProductOK: function (addProducts, index) {
//       var start = index - 1;
//       var j = addProducts.length - (products.length - start);
//       for (var i = 0; i < j; i++) {
//         products.add(new Product());
//       }
//       if (j > 0) this.render();

//       for (var i = 0; i < addProducts.length; i++) {
//         var addProduct = addProducts[i];
//         addProduct.index = start + 1;
//         addProduct.readonly = true;
//         if (start < products.length) {
//           var product = products.at(start);
//           product.set(addProduct);
//         }
//         start++;
//       };
//     },
//     //计算总金额
//     calCountAmt: function () {
//       console.log("calCountAmt")
//       this.amtCount = 0;
//       this.totalCount = 0;

//       for (var i = 0; i < products.length; i++) {
//         var product = products.at(i);
//         this.totalCount += Number(product.get("productCount"));
//         this.amtCount += product.get("eachSaleAmt");
//       }

//       this.$("#SaleAmt").val(this.amtCount.toFixed(2));
//       this.$("#spanTotalCount").val(this.totalCount.toFixed(2));
//       //计算折后金额
//       this.calDiscountAmt();
//     },
//     //计算折后金额 默认填充实收金额
//     calDiscountAmt: function () {
//       this.otherFee = Number(this.$("#OtherFee").val());
//       this.amtCount = Number(this.$("#SaleAmt").val());
//       this.faReceAmt = Number(this.otherFee) + Number(this.amtCount);
//       $("#ReceAmt").val(this.faReceAmt.toFixed(2));
//       console.log("calDiscountAmt");
//     },
//     setFocus: function (index, selecter) {
//       for (var i = 0; i < products.length; i++) {
//         var product = products.at(i);
//         if (product.get("index") == index) {
//           product.trigger("focus", selecter);
//         }
//       }
//     },
//     SaveDataToList: function () {
//       this.SaveData(1);
//     },
//     SaveData: function (IsToList) {
//       $(".button").hide();
//       if (ValidateForm()) {
//         $("#IsToList").val(IsToList);

//         var productData = [];
//         for (var i = 0; i < products.length; i++) {
//           var product = products.at(i);
//           productData.push(product);
//         }

//         $("#productData").val(JSON.stringify(productData));

//         var isPrint = $("#chkPrint").attr("checked");
//         if (isPrint) {
//           $("#IsPrint").val(1);
//           $("form").submit();
//         } else {
//           $("#IsPrint").val(0);
//           $("form").submit();
//         };
//       }
//       else {
//         $(".button").show();
//       }
//       parent.UpdateTabFirst();
//     },
//     copyFromSale: function (copySaleId) {

//       $.post("/Sale/Get", { SaleId: copySaleId }, function (sale, resultState) {
//         if (resultState == "success") {
//           $('#ClientId').combobox("select", sale.clientId);
//           if (sale.isNeedDeliverGoods == 1) {
//             $("input[name='IsNeedDeliverGoods']").attr("checked", "checked");
//           }
//           else {
//             $("input[name='IsNeedDeliverGoods']").removeAttr("checked");
//           }

//           chgDeliverGoods();
//           var jsonn = [];
//           for (var i = 0; i < sale.saleItems.length; i++) {
//             var saleItem = sale.saleItems[i];
//             jsonn.push(saleItem);
//           }
//           SelectProductOK(jsonn, 1);
//         }

//       }, "json");
//     }
//   });

//   productView = new ProductView;
// });

// function delSel() {
//   productView.delSels();
// }
